let _Vue = ''
export default class VueRouter {
  static install (Vue) { // 第一个参数为vue的构造函数
    // 1 判断当前插件是否被安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    // 2 把Vue的构造函数记录在全局
    _Vue = Vue
    // 3 把创建Vue的实例传入的router对象注入到Vue实例
    // _Vue.prototype.$router = this.$options.router
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      }
    })
  }

  constructor (options) {
    this.options = options // 路由配置
    this.routeMap = {} // key对应路由路劲 value对应组件
    this.data = _Vue.observable({
      current: '/'
    })
    this.init()
  }

  init () {
    this.createRouteMap(this.options)
    this.initEvent()
    this.createComponent()
  }

  initEvent () {
    // 监听前进后退
    if (this.options.mode === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    } else {
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash.substr(1)
      })
    }
  }

  createRouteMap (options) {
    options.routes.forEach(item => {
      this.routeMap[item.path] = item.component
    })
  }

  createComponent () {
    const self = this
    _Vue.component('router-link', {
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.handleClick.bind(333)
          }
        }, [this.$slots.default])
      },
      props: {
        to: String
      },
      methods: {
        handleClick (e) {
          const mode = this.$router.options.mode
          // 改变地址栏参数
          if (mode === 'history') {
            history.pushState({}, '', this.to)
          } else {
            location.hash = '#' + this.to
          }
          // 切换对应组件
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    _Vue.component('router-view', {
      render (h) {
        const currentComponent = self.routeMap[self.data.current]
        if (!currentComponent) {
          return h(self.routeMap['*'])
        } else {
          return h(currentComponent)
        }
      }
    })
  }
}
